/**
 * 防重复提交Composable
 * 包含：加载状态、防抖、错误处理
 */
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

/**
 * 使用防重复提交hook
 * @param {Function} submitFn - 提交函数
 * @param {Object} options - 配置选项
 * @returns {Object} - 提交相关的状态和方法
 */
export function useSubmit(submitFn, options = {}) {
  const {
    debounceTime = 2000, // 防抖时间（毫秒）
    successMessage = '操作成功',
    errorMessage = '操作失败',
    showMessage = true, // 是否显示提示消息
    onSuccess = null, // 成功回调
    onError = null // 失败回调
  } = options

  // 状态
  const loading = ref(false)
  const error = ref(null)
  const lastSubmitTime = ref(0)

  // 计算属性
  const canSubmit = computed(() => {
    const now = Date.now()
    return !loading.value && (now - lastSubmitTime.value) > debounceTime
  })

  const remainingTime = computed(() => {
    const now = Date.now()
    const elapsed = now - lastSubmitTime.value
    const remaining = debounceTime - elapsed
    return Math.max(0, Math.ceil(remaining / 1000))
  })

  /**
   * 提交函数
   */
  const submit = async (...args) => {
    // 检查是否可以提交
    if (!canSubmit.value) {
      const message = `请等待${remainingTime.value}秒后再试`
      if (showMessage) {
        ElMessage.warning(message)
      }
      return {
        success: false,
        message,
        error: 'DEBOUNCE'
      }
    }

    // 设置加载状态
    loading.value = true
    error.value = null
    lastSubmitTime.value = Date.now()

    try {
      // 执行提交函数
      const result = await submitFn(...args)

      // 成功处理
      if (showMessage && successMessage) {
        ElMessage.success(successMessage)
      }

      if (onSuccess) {
        onSuccess(result)
      }

      return {
        success: true,
        data: result
      }
    } catch (err) {
      // 错误处理
      error.value = err
      const message = err.message || errorMessage

      if (showMessage) {
        ElMessage.error(message)
      }

      if (onError) {
        onError(err)
      }

      return {
        success: false,
        message,
        error: err
      }
    } finally {
      // 延迟重置加载状态，确保防抖效果
      setTimeout(() => {
        loading.value = false
      }, 500)
    }
  }

  /**
   * 重置状态
   */
  const reset = () => {
    loading.value = false
    error.value = null
    lastSubmitTime.value = 0
  }

  return {
    // 状态
    loading,
    error,
    canSubmit,
    remainingTime,

    // 方法
    submit,
    reset
  }
}

/**
 * 使用表单提交hook（增强版）
 * @param {Object} formRef - 表单ref
 * @param {Function} submitFn - 提交函数
 * @param {Object} options - 配置选项
 */
export function useFormSubmit(formRef, submitFn, options = {}) {
  const submitHook = useSubmit(submitFn, options)

  /**
   * 带表单验证的提交
   */
  const submitWithValidation = async (...args) => {
    if (!formRef.value) {
      ElMessage.warning('表单未初始化')
      return { success: false, error: 'FORM_NOT_READY' }
    }

    try {
      // 验证表单
      const valid = await formRef.value.validate()
      
      if (!valid) {
        ElMessage.warning('请检查表单填写是否正确')
        return { success: false, error: 'VALIDATION_FAILED' }
      }

      // 提交
      return await submitHook.submit(...args)
    } catch (validationError) {
      console.error('表单验证失败:', validationError)
      ElMessage.warning('请检查表单填写是否正确')
      return { success: false, error: 'VALIDATION_ERROR' }
    }
  }

  /**
   * 重置表单和提交状态
   */
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    submitHook.reset()
  }

  return {
    ...submitHook,
    submitWithValidation,
    resetForm
  }
}

